package NG::Gen::Task::Standart;
use strict;
use warnings;
use utf8;

use NG::Sys::App;
use NG::Gen::Battle::Side;
use NG::Gen::Battle::Battle;

use NG::Sys::Data;
use NG::Sys::Datetime;
our @ISA = qw(NG::Gen::Task::Task);

sub mutate {
	my $self = shift;
	my $list = app->reference("standart_enemy")->get_list({user_cat => $self->{user}->category});
	my $cur = $list->[rand @$list];
	$self->{param}{units} = $cur->{troop}{units};
	$self->{param}{troop_id} = $cur->{entry};
	$self->{param}{title} = $cur->{title};
	return 0;
}
sub make_context {
	my $self = shift;
	my $ref = app->reference("units");
	my @el;
	my @ul;
	for(@{$self->param->{units}}){
		if($_->{count}){
			push @el, {
				type => copy_hash($ref->get_by_key($_->{unit}),"entry","type","title","img"),
				count => $_->{count},
			};
		}
	}
	for(@{$self->{leader}->units->list}){
		if($_->{count}){
			push @ul, {
				type => copy_hash($ref->get_by_key($_->{proto_id}),"entry","type","title","img"),
				count => $_->{count},
			};
		}
	}
	return {
		enemy => \@el,
		units => \@ul,
	};
}

sub before_done {
	my $self = shift;

	my $s1 = NG::Gen::Battle::Side->new_from_user($self->{user},$self->{leader});
	my $s2 = NG::Gen::Battle::Side->new_from_standart($self->param->{troop_id});

	my @log;
	app->mark_time("battle");
	my $res = calc_battle($s1,$s2,\@log);
	my $spend = app->mark_time("battle");
	push @log,["stat",$spend,1/$spend,scalar @log,@log/$spend];
	my $text;
	if($res == 1){
		$text = "Победа";
	}
	elsif($res == 2){
		$text = "Поражение";
	}
	else{
		$text = "Ничья";
	}
	my $row = {
		title => "$s1->{title} vs. $s2->{title}",
		date => unixtime2timestamp(),
		result => $res,
		log => \@log,
		side => $self->{task}->context,
	};
	my $log_id = app->store("battle_log")->insert($row);

	delete @{$row}{("log","side")};
	$row->{log_id} = $log_id;
	$row->{enemy_id} = 0;

	my $entry = $self->{user}->lbattle->insert($row);
	$self->{add} = {
				log_id => $log_id,
				entry => $entry,
			};

	$self->{result} = $text;

	return 0;
}
sub after_done {
	my $self = shift;
	$self->refresh_user(1,1);
	return 0;
}


1;
